import os

from demos.jingbit import file_utils
from paddlespeech.cli.tts import TTSExecutor
from paddlespeech.cli.asr import  ASRExecutor
from scipy.signal import resample

class MyPaddleSpeech:
    def __init__(self):
        self.tts_executor = TTSExecutor()
        self.asr_executor = ASRExecutor()
        self.output_path = "D:\\WEMedia"

    def txt2audio(self, txt_file, lang):
        text = txt_file.read().decode('utf-8')
        output_path = os.path.join(self.output_path, file_utils.get_file_name(txt_file) + ".wav")
        self.tts_executor(text=text, output=output_path, lang=lang)
        return output_path

    def audio2txt(self, audio_file, lang):
        out_audio_file= os.path.join(self.output_path, file_utils.get_file_name(audio_file) + ".wav")
        audio_file=file_utils.convert216k(audio_file,out_audio_file)
        if not audio_file:
            print(audio_file + "转换失败")
            return "转换失败!"
        text = self.asr_executor(audio_file=audio_file)
        output_path = os.path.join(self.output_path, file_utils.get_file_name(audio_file) + ".txt")
        self.tts_executor(text=text, output=output_path, lang=lang)
        return output_path

    def process_file(self, file, lang):
        if file_utils.is_text(file):
            return self.txt2audio(file, lang)
        elif file_utils.is_audio(file):
            return self.audio2txt(file, lang)
        elif file_utils.is_video(file):
            audio_output_file = os.path.join(self.output_path, file_utils.get_file_name(file) + ".wav")
            video_output_file = os.path.join(self.output_path, file_utils.get_file_name(file) + ".mp4")
            success = file_utils.split_video(file, audio_output_file, video_output_file)
            if not success:
                print(file + "分割失败")
                return "分割失败!"
            txt_file = self.audio2txt(audio_output_file, lang)
            audio_file = self.txt2audio(txt_file, lang)
            output_file = os.path.join(self.output_path, file_utils.get_file_name(file))
            # 合并音频和视频
            success = file_utils.merge_audio_video(audio_file, video_output_file, output_file)
            if not success:
                print(file + "合成失败")
                return "合成失败!"
            return output_file

    def start(self, parent_file, lang):
        if os.path.isdir(parent_file):
            for file in os.listdir(parent_file):
                self.process_file(file, lang)
        else:
            self.process_file(parent_file, lang)


if __name__ == '__main__':
    speech=MyPaddleSpeech()
    speech.start(r"D:\output.wav","en")